@namespace LLMAgentTUI.Components

@using System
@using System.Collections.Generic
@using System.Linq
@using Microsoft.AspNetCore.Components
@using RazorConsole.Components
@using Spectre.Console
@using LLMAgentTUI.Services

@inject IChatService ChatService

<Figlet Content="ChatBot" />

<Padder Padding="@(new(1, 0, 0, 0))">
	<Rows>
		@if (_messages.Count == 0)
		{
			<Markup Content="No messages yet. Type a message below to start chatting." Foreground="@Color.Grey" />
		}
		else
		{
			foreach (var message in _messages)
			{
				<Padder Padding="@(new(0, 1, 0, 0))">
					<Markup Content="@($"{(message.IsUser ? "You" : "Bot")}")" Foreground="@(message.IsUser? Color.Green: Color.Blue)" />
					<Markup Content=" " />
					<Markdown Content="@message.Content" />
				</Padder>
			}
		}

		@if (_isProcessing)
		{
			<Padder Padding="@(new(0, 0, 0, 1))">
				<Columns>
					<RazorConsole.Components.Spinner SpinnerType="@Spectre.Console.Spinner.Known.Dots" />
					<Markup Content="AI is thinking..." Foreground="@Color.Grey" Decoration="@Decoration.Italic" />
				</Columns>
			</Padder>
		}
	</Rows>
</Padder>

<TextInput @bind-Value="_currentInput" Placeholder="Type your message here..." OnSubmit="SendMessage" Expand="true" onclick="SendMessage" />

<Align Horizontal="@HorizontalAlignment.Center">
	<Markup Content="AI-Powered Console ChatBot • Tab to change focus • Enter to submit • Ctrl+C to exit" Foreground="@Color.Grey58" />
</Align>

@code {
	private List<ChatMessage> _messages = new();
	private string _currentInput = string.Empty;
	private bool _isProcessing = false;

	private async Task SendMessage()
	{
		if (string.IsNullOrWhiteSpace(_currentInput))
		{
			return;
		}

		var userMessage = _currentInput.Trim();
		_currentInput = string.Empty;

		_messages.Add(new ChatMessage
		{
			Content = userMessage,
			IsUser = true
		});

		StateHasChanged();

		_isProcessing = true;
		StateHasChanged();

		try
		{
			var response = await ChatService.SendMessageAsync(userMessage);

			_messages.Add(new ChatMessage
			{
				Content = response,
				IsUser = false
			});
		}
		catch (Exception ex)
		{
			_messages.Add(new ChatMessage
			{
				Content = $"[red]Error: {ex.Message}[/]",
				IsUser = false
			});
		}
		finally
		{
			_isProcessing = false;
			StateHasChanged();
		}
	}

	public class ChatMessage
	{
		public required string Content { get; set; }
		public bool IsUser { get; set; }
	}
}
